<?php

/**
 * 授权公众号上传图片并返回二维码
 * 使用微信客户端扫码即可在对应公众号
 * 响应并回复下发此图片
 *
 */
namespace App\Http\Controllers\OpenWeChat;

use App\Http\Controllers\ApiController;

use App\Http\Requests\OpenWechat\ImageShareStoreRequest;
use App\Models\OpenWechat\Authorizer;
use App\Models\OpenWechat\ScanEvent;

use App\Services\OpenWechat\MaterialSave;
use App\Services\OpenWechat\QrCode;
use Illuminate\Http\UploadedFile;
use Intervention\Image\ImageManagerStatic;


class ImageShareController extends ApiController
{
    private $try_count = 0;

    const MAX_TRY_COUNT = 3;

    const DEFAULT_WIDTH = 500;

    const DEFAULT_HEIGHT = null;

    /**
     * @link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726 - 微信公众号 素材管理文档
     * @link https://www.easywechat.com/docs/master/zh-CN/basic-services/media - easywechat 临时素材上传接口
     *
     * @param ImageShareStoreRequest $request
     *
     * @return array|\Illuminate\Http\Response|mixed
     * @throws \Exception
     */
    public function store(ImageShareStoreRequest $request)
    {
        $image = $request->file('image');

        /** @var Authorizer $authorizer */
        $authorizer = Authorizer::findByAppId($request->appid);
            $this->checkItemExist($authorizer, 'appid');

        $temp_img = $this->copyImageToStorage( $image);

        // 已经限制图片不能超过2MB不需要压缩了
//        Compress::handle($temp_img, $request->width ?: self::DEFAULT_WIDTH, $request->height);

        $material = $this->tryUploadMaterial($authorizer, $temp_img);

        /** @var ScanEvent $scan_event */
        $scan_event = $this->createNewScanEvent($authorizer, $material['media_id']);

        $reply_id = $scan_event->id;

        $qr_code_url = (new QrCode)->tempUrl($request->appid, $scan_event->getSceneValue());

        if ($request->type === 'url') {
            return $this->response(compact('qr_code_url', 'reply_id'));
        }

        // else return png
        $qr_code = ImageManagerStatic::make($qr_code_url);

        return $qr_code->response('png');
    }

    /**
     * @param $authorizer
     * @param $media_id
     * @return mixed
     */
    private function createNewScanEvent(Authorizer $authorizer, string $media_id)
    {
        $event_reply = (new ScanEvent)->create([
            'type'    => ScanEvent::TYPE_REPLY_IMAGE,
            'value'   => $authorizer->id,
            'data' => [
                'media_id' => $media_id
            ]
        ]);

        return $event_reply;
    }


    /**
     * @param Authorizer $authorizer
     * @param $image_path
     * @return \EasyWeChat\Kernel\Support\Collection
     * @throws \Exception
     */
    private function tryUploadMaterial(Authorizer $authorizer, string $image_path)
    {
        try {
            $material = (new MaterialSave($authorizer))->uploadTempImage($image_path);
            @unlink($image_path);
            return $material;
        } catch (\Exception $exception) {
            if ($this->try_count++ < self::MAX_TRY_COUNT) {
                return $this->tryUploadMaterial($authorizer, $image_path);
            }
            @unlink($image_path);
            throw $exception;
        }
    }

    /**
     * @param $image
     * @return string
     */
    private function copyImageToStorage(UploadedFile $image)
    {
        $temp_img = storage_path(uniqid() . 'tmp_img.jpg');

        copy($image->getRealPath(), $temp_img);

        return $temp_img;
    }


    /**
     * @deprecated （app端 手动清除）
     *
     * 查询是否已被扫
     * @param $replay_id
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function show($replay_id)
    {
        $reply = ScanEvent::find($replay_id);
            $this->checkItemExist($reply);

        return $this->response(compact('reply'));
    }

}
